package com.ufind.businesslog.demo.domain;

import com.ufind.businesslog.api.BusinessLog;
import com.ufind.businesslog.demo.dto.DefaultBusinessLogDTO;
import com.ufind.businesslog.demo.infra.repository.sql.DefaultBusinessLogMapper;
import com.ufind.businesslog.demo.uitls.UUIDUtils;

import javax.inject.Inject;
import javax.inject.Named;
import java.util.Collections;
import java.util.Map;

import static com.ufind.businesslog.api.constant.ContextKeyConstant.BUSINESS_OPERATION_IP;
import static com.ufind.businesslog.api.constant.ContextKeyConstant.BUSINESS_OPERATION_USER;

/**
 * User: zjzhai Date: 12/12/13 Time: 11:23 AM
 */
@Named
public class DefaultBusinessLog extends DefaultBusinessLogDTO {

    @Inject
    private DefaultBusinessLogMapper defaultBusinessLogMapper;

    public synchronized static DefaultBusinessLog createBy(BusinessLog businessLog) {
        DefaultBusinessLog myBusinessLog = new DefaultBusinessLog();
        Map<String, Object> context = businessLog.getContext();

        if (context.get(BUSINESS_OPERATION_USER) != null) { //设置操作人
            myBusinessLog.setUser((String) context.get(BUSINESS_OPERATION_USER));
        }

//        if (context.get(BUSINESS_OPERATION_TIME) != null) { //设置操作时间
//            myBusinessLog.setTime((Date) context.get(BUSINESS_OPERATION_TIME));
//        }

        if (context.get(BUSINESS_OPERATION_IP) != null) { //设置操作IP
            myBusinessLog.setIp((String) context.get(BUSINESS_OPERATION_IP));
        }

        myBusinessLog.setLog(businessLog.getLog()); //设置操作日志内容
        myBusinessLog.setCategory(businessLog.getCategory()); //设置操作类别

        context = Collections.unmodifiableMap(context);

        return myBusinessLog;
    }

    /**
     * 日志的保存操作
     * @param log
     * @return
     */
    public boolean save(DefaultBusinessLog log) {
        log.setId(UUIDUtils.get32UUIDAsLowerCase());
        return defaultBusinessLogMapper.insertSelective(log) == 1 ? true : false;
    }
}
